<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\Traits\EventRecordTable;

class EventRecord extends Model
{
    use HasFactory;
    use EventRecordTable;

    // 表名
    protected $table = "event_records";
    
    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'user_id', 'event', 'model_id'
    ];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        // 初始化分表处理
        $this->init();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function scopeStart($query, $value)
    {
        if (empty($value)) {
            return $query;
        }
        return $query->where('created_at', '>=', $value);
    }

    public function scopeEnd($query, $value)
    {
        if (empty($value)) {
            return $query;
        }
        return $query->where('created_at', '<=', $value);
    }

    public function eventer()
    {
        return $this->belongsTo(Event::class, 'event', 'label');
    }

    public function getModelTitleAttribute()
    {
        $activity_events = [
            'click-activity'
        ];
        $vehicle_events = [
            'click-hotCar',
        ];
        $banner_events = [
            'click-indexBanner',
            'click-myBanner'
        ];
        if (in_array($this->event, $activity_events)) {
            return Activity::where('id',$this->model_id)->value('title');
        }else if(in_array($this->event, $vehicle_events)){
            return Vehicle::where('id',$this->model_id)->value('name');
        }else if(in_array($this->event, $banner_events)){
            return Banner::where('id',$this->model_id)->value('title');
        }else{
            return '';
        }
    }
}
